import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { AuthController } from '../controllers/AuthController';
import { authMiddleware } from '../middleware/auth';
import { User } from '@weubi/shared';

// 扩展 Hono Context 类型
type Variables = {
  user: User;
};

export const authRoutes = new Hono<{ Variables: Variables }>();
const authController = new AuthController();

// 验证模式
const registerSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(255),
  password: z.string().min(6).max(100),
});

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

const changePasswordSchema = z.object({
  currentPassword: z.string().min(1),
  newPassword: z.string().min(6).max(100),
});

const updateProfileSchema = z.object({
  name: z.string().min(1).max(255).optional(),
  avatar: z.string().url().optional(),
  preferences: z.object({
    theme: z.enum(['light', 'dark']).optional(),
    language: z.string().optional(),
    timezone: z.string().optional(),
    notifications: z.object({
      email: z.boolean().optional(),
      push: z.boolean().optional(),
    }).optional(),
  }).optional(),
});

// 用户注册
authRoutes.post('/register', zValidator('json', registerSchema), async (c) => {
  try {
    const data = c.req.valid('json');
    const result = await authController.register(data);
    
    return c.json({
      success: true,
      data: result,
      message: 'User registered successfully',
    }, 201);
  } catch (error) {
    console.error('Register error:', error);
    
    if (error instanceof Error && error.message.includes('already exists')) {
      return c.json({
        success: false,
        error: 'Email already exists',
        message: 'A user with this email already exists',
      }, 409);
    }
    
    return c.json({
      success: false,
      error: 'Registration failed',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 用户登录
authRoutes.post('/login', zValidator('json', loginSchema), async (c) => {
  try {
    const data = c.req.valid('json');
    const ip = c.req.header('x-forwarded-for') || c.req.header('x-real-ip') || 'unknown';
    
    const result = await authController.login(data, ip);
    
    return c.json({
      success: true,
      data: result,
      message: 'Login successful',
    });
  } catch (error) {
    console.error('Login error:', error);
    
    if (error instanceof Error && error.message.includes('Invalid credentials')) {
      return c.json({
        success: false,
        error: 'Invalid credentials',
        message: 'Email or password is incorrect',
      }, 401);
    }
    
    return c.json({
      success: false,
      error: 'Login failed',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 刷新令牌
authRoutes.post('/refresh', zValidator('json', z.object({
  refreshToken: z.string(),
})), async (c) => {
  try {
    const { refreshToken } = c.req.valid('json');
    const result = await authController.refreshToken(refreshToken);
    
    return c.json({
      success: true,
      data: result,
      message: 'Token refreshed successfully',
    });
  } catch (error) {
    console.error('Refresh token error:', error);
    return c.json({
      success: false,
      error: 'Token refresh failed',
      message: error instanceof Error ? error.message : 'Invalid refresh token',
    }, 401);
  }
});

// 用户登出
authRoutes.post('/logout', authMiddleware, async (c) => {
  try {
    const user = c.get('user');
    await authController.logout(user.id);
    
    return c.json({
      success: true,
      message: 'Logout successful',
    });
  } catch (error) {
    console.error('Logout error:', error);
    return c.json({
      success: false,
      error: 'Logout failed',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取当前用户信息
authRoutes.get('/me', authMiddleware, async (c) => {
  try {
    const user = c.get('user');
    const profile = await authController.getProfile(user.id);
    
    return c.json({
      success: true,
      data: profile,
    });
  } catch (error) {
    console.error('Get profile error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch profile',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 更新用户资料
authRoutes.put('/me', authMiddleware, zValidator('json', updateProfileSchema), async (c) => {
  try {
    const user = c.get('user');
    const data = c.req.valid('json');
    const profile = await authController.updateProfile(user.id, data);
    
    return c.json({
      success: true,
      data: profile,
      message: 'Profile updated successfully',
    });
  } catch (error) {
    console.error('Update profile error:', error);
    return c.json({
      success: false,
      error: 'Failed to update profile',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 修改密码
authRoutes.post('/change-password', authMiddleware, zValidator('json', changePasswordSchema), async (c) => {
  try {
    const user = c.get('user');
    const data = c.req.valid('json');
    await authController.changePassword(user.id, data);
    
    return c.json({
      success: true,
      message: 'Password changed successfully',
    });
  } catch (error) {
    console.error('Change password error:', error);
    
    if (error instanceof Error && error.message.includes('Current password is incorrect')) {
      return c.json({
        success: false,
        error: 'Invalid current password',
        message: 'Current password is incorrect',
      }, 400);
    }
    
    return c.json({
      success: false,
      error: 'Failed to change password',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 验证令牌（用于前端检查）
authRoutes.get('/verify', authMiddleware, (c) => {
  const user = c.get('user');
  return c.json({
    success: true,
    data: {
      valid: true,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        role: user.role,
      },
    },
  });
});
